var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient
var config = require('../config/db')
var passport = require('passport')
const mongodb = require('mongodb')
const jwt = require('jsonwebtoken')
/*添加收藏 */
router.post('/AddCollection', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要添加的订单商品信息
  let collection = req.body.collection
  console.log('MyCollection: ', collection);
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  //创建订单对象
  let NewCollection = {
    "userId": req.user._id,
    "products": collection,
    "addTime ": new Date(),
    "state": 1
  }
  //执行添加订单的操作
  let results = await db.collection('AllCollection').insertOne(NewCollection)
  //判断是否添加成功
  if (results.acknowledged) {
    let collections = await db.collection('AllCollection').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
    console.log('collections', collections[0]._id)
    res.json({ code: 200, message: 'ok', data: collections[0]._id });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});
//查看收藏
router.get('/Getcollections', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  let collections = await db.collection('AllCollection').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
  if (collections.length >= 0) {
    res.json({ code: 200, message: 'ok', data: collections });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});
//删除收藏
router.delete('/deletecollection', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  let { id } = req.query                         //获取需要删除的购物车信息id
  let client = await MongoClient.connect(config.url)     //获取数据库连接对象
  let db = client.db()
  let results = await db.collection('AllCollection').deleteOne({ _id: new mongodb.ObjectId(id) })//执行删除购物车的操作
  console.log(' results: ', results)
  //判断是否删除成功
  if (results.acknowledged) {
    res.json({ code: 200, message: 'ok' });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});
module.exports = router;